package com.baosight.risk.service.xtzy.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.service.soa.XServiceManager;
import com.baosight.risk.api.fltd.FltdNoticeToOAService;
import com.baosight.risk.api.xtzy.IXtzyUserService;
import com.baosight.risk.base.mapper.BaseMapper;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.result.AjaxResult;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.fltd.FltdTaskMapper;
import com.baosight.risk.mapper.quartz.SysSyncEmpleeMapper;
import com.baosight.risk.mapper.xtzy.XtzyUserMapper;
import com.baosight.risk.service.constant.Constant;
import com.baosight.risk.service.fltd.entity.FltdTask;
import com.baosight.risk.service.quartz.entity.SyncEmpleeEntitiy;
import com.baosight.risk.service.xtzy.entity.XtzyUser;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

/**
 * 类 名: XtzyUserServiceImpl
 * 描 述:
 * 作 者: 黎秋荣
 * 创 建：2019年04月25日
 * 版 本：v2.2.0
 * 历 史: (版本) 作者 时间 注释
 */
@Slf4j
@Service
public class XtzyUserServiceImpl extends BaseServiceImpl<XtzyUser> implements IXtzyUserService {

    @Autowired
    private XtzyUserMapper userMapper;
    @Autowired
    private FltdTaskMapper fltdTaskMapper;
    @Autowired
    private FltdNoticeToOAService fltdNoticeToOAService;
    
    
    @Override
    public Integer updateExpireDate() {
        return userMapper.updateExpireDate();
    }

    @Autowired
    private SysSyncEmpleeMapper sysSyncEmpleeMapper;

    @Override
    public BaseMapper getMapper() {
        return userMapper;
    }

    @Override
    public List<XtzyUser> selectUser(XtzyUser user) {
        return userMapper.selectUser(user);
    }


    @Override
	public XtzyUser selectByUserType(String phoneCode, String userType) {
    	XtzyUser param = new XtzyUser();
    	param.setPhoneCode(phoneCode);
    	param.setUserType(userType);
		return userMapper.selectOne(param);
	}

	@Override
    public XtzyUser selectByName(String userCode) {
        return userMapper.selectByName(userCode);
    }

    @Override
    public XtzyUser getUserByStatus(String userCode) {
        XtzyUser user = selectByName(userCode);
        if (user != null) {
            if ("10".equals(user.getStatus())) {
                return user;
            }
        }
        return null;
    }

    /**
     * 新增用户
     *
     * @param user 用户
     * @return
     */
    @Override
    public Integer insertUser(XtzyUser user) {
    	if(Constant.USER_TYPE.TEMP.equals(user.getUserType())){
        	XtzyUser param = new XtzyUser();
        	param.setPhoneCode(user.getPhoneCode());
        	param.setUserType(user.getUserType());
    		int count = userMapper.selectCount(param);
    		if(count>0){
    			throw new RuntimeException("请返回到人员授权页面，点击（新增）按钮，添加人员权限！");
    		}
    	}
        int insert = userMapper.insert(user);
        // 修改用户过期为永久
        userMapper.updateExpireDate();
        return insert;
    }

    /**
     * 根据id禁用组织机构
     *
     * @param ids 用户ID
     * @return
     */
    @Override
    public AjaxResult deleteById(List<String> ids, String status) throws Exception {
        for (String id : ids) {
            XtzyUser user = userMapper.selectByPrimaryKey(id);
            if (status.equals(user.getStatus())) {
                return AjaxResult.error("状态已经是禁用，不可以再禁用！");
            }
            deleteUser(user);
        }
        Integer row = userMapper.deleteById(ids, status);
        if (row > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }

    }

    /**
     * 根据id禁用组织机构
     *
     * @param ids 用户ID
     * @return
     */
    @Override
    public AjaxResult openById(List<String> ids, String status) throws Exception {
        for (String id : ids) {
            XtzyUser user = userMapper.selectByPrimaryKey(id);
            if (status.equals(user.getStatus())) {
                return AjaxResult.error("状态已经是禁用，不可以再禁用！");
            }
            addUser(user);
        }
        // 修改用户过期为永久
        userMapper.updateExpireDate();
        Integer row = userMapper.deleteById(ids, status);
        if (row > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    @Override
    public List<SyncEmpleeEntitiy> getEmpleeFromOtherDB(SyncEmpleeEntitiy syncEmpleeEntitiy) {
        List<SyncEmpleeEntitiy> result = sysSyncEmpleeMapper.getEmpleeFromOtherDB(syncEmpleeEntitiy);
        return result;
    }

    public void addUser(XtzyUser user) throws Exception {
        EiInfo eiInfo = new EiInfo();
        eiInfo.set(EiConstant.serviceId, "S_XS_15");
        EiBlock eiBlock = new EiBlock("result");
        List list = new ArrayList();
        Map map = new HashMap();
        map.put("loginName", user.getUserCode());
        map.put("password","admin123");
        map.put("rePass", "admin123");
        map.put("userType", "USER");
        map.put("userName", StringUtils.isEmpty(user.getUserDesc()) ? " " : user.getUserDesc());
        map.put("mobile", StringUtils.isEmpty(user.getPhoneCode()) ? " " : user.getPhoneCode());
        map.put("email", StringUtils.isEmpty(user.getEmail()) ? " " : user.getEmail());
        map.put("recCreator", "admin");
        list.add(map);
        eiBlock.setRows(list);
        eiInfo.setBlock(eiBlock);
        EiInfo outInfo = XServiceManager.call(eiInfo);
        System.out.println(JSONObject.fromObject(outInfo));
        if (outInfo.getStatus() != 0) {
            log.error("添加数据异常", outInfo);
            throw new Exception("数据有误！");
        }
    }

    public void deleteUser(XtzyUser user) throws Exception {
        EiInfo eiInfo = new EiInfo();
        eiInfo.set(EiConstant.serviceId, "S_XS_16");
        EiBlock eiBlock = new EiBlock("result");
        List list = new ArrayList();
        Map map = new HashMap();
        map.put("loginName", user.getUserCode());
        map.put("recRevisor", "admin");
        list.add(map);
        eiBlock.setRows(list);
        eiInfo.setBlock(eiBlock);
        EiInfo outInfo = XServiceManager.call(eiInfo);
        System.out.println(JSONObject.fromObject(outInfo));
        if (outInfo.getStatus() != 0) {
            log.error("删除数据异常", outInfo);
            throw new Exception("数据有误！");
        }
    }

    @Override
    public void addUserToIplat(XtzyUser user) throws Exception {
        addUser(user);
    }

	@Override
	public Integer changePwd(String userCode,String oldPwd,String newPwd){
		EiInfo eiInfo = new EiInfo();
	    eiInfo.set(EiConstant.serviceId,"S_XS_104");
	    eiInfo.set("loginName", userCode);
	    eiInfo.set("oldPassword", oldPwd);
	    eiInfo.set("password", newPwd);
	    eiInfo.set("rePassword", newPwd);
	    EiInfo outInfo = XServiceManager.call(eiInfo);
        if (outInfo.getStatus() != 0) {
        	return 0;
        }
        return 1;
	}

	@Override
	public void deleteOA(List<String> ids) throws Exception{
		// TODO Auto-generated method stub
        for (String id : ids) {
            XtzyUser user = userMapper.selectByPrimaryKey(id);
            fltdNoticeToOAService.synchroOA(user.getUserCode());
            
/*    		FltdTask param = new FltdTask();
    		param.setCurrUserCode(user.getUserCode());
    		param.setStatus("colse");
            List<FltdTask> closes = fltdTaskMapper.select(param);
    		param.setStatus("finish");
            List<FltdTask> finishs = fltdTaskMapper.select(param);
            finishs.addAll(closes);*/

        }

	}
   
}
